package com.qcu.task;

import com.qcu.entity.Appointment;
import com.qcu.entity.AppointmentTemp;
import com.qcu.service.AppointmentService;
import com.qcu.service.AppointmentTempService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Name: MyComputer
 * @ClassName AppointmentTask
 * @Description:
 * @date 2025/2/11 16:51
 */
@Service
@Slf4j
public class AppointmentTask {
    @Resource
    AppointmentTempService appointmentTempService;
    @Resource
    AppointmentService appointmentService;
    @Resource
    JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;

//    @Scheduled(cron = "0 0 9-17 * * ?") // 每天早上9点到晚上5点之间每隔一小时执行一次
    //每分钟执行一次
    @Scheduled(cron = "0 0/1 * * * ?")
    public void disposeAppointment() {
        // 获取temp中的数据
        List<AppointmentTemp> list = appointmentTempService.list();
        log.info("获取到temp中的数据：" + list);
        if (list.size() != 0){
            List<Appointment> toList = list.stream().map(temp -> {
                Appointment appointment = new Appointment();
                appointment.setAgreeTime(temp.getAgreeTime());
                appointment.setDoctorId(temp.getDoctorId());
                appointment.setEmail(temp.getEmail());
                appointment.setGender(temp.getGender());
                appointment.setId(temp.getId());
                appointment.setInhabitantId(temp.getInhabitantId());
                appointment.setItem(temp.getItem());
                appointment.setResult(temp.getResult());
                appointment.setState(temp.getState());
                appointment.setSubTime(temp.getSubTime());
                appointment.setSubscribe(temp.getSubscribe());
                return appointment;
            }).collect(Collectors.toList());
            // 获取邮箱数据（居民）
            List<String> emails = appointmentTempService.getEmailOfDoctor();
            log.info("获取到temp中的邮箱数据：" + emails);
            // 向获得的邮箱发送邮件（提醒）
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            String[] to = emails.toArray(new String[0]);
            message.setTo(to);
            message.setSubject("预约通知");
            message.setText("您有新的预约请注意查看，请前往系统预约管理界面查看");
            javaMailSender.send(message);
            log.info("开始向获得的邮箱发送邮件（提醒）");
            // 将temp中的数据插入appointment中
            appointmentService.saveBatch(toList);
            log.info("将temp中的数据插入appointment中");
            // 删除temp中数据
            appointmentTempService.remove(null);
            log.info("删除temp中数据");
        }

    }
}
